#![cfg_attr(feature = "axstd", no_std)]
#![cfg_attr(feature = "axstd", no_main)]

extern crate axplat_aarch64_phytium_pi;

#[cfg(feature = "axstd")]
use axstd::println;

mod canfd;
mod cem5826m11;
mod fan;
mod led;
mod utils;

#[cfg_attr(feature = "axstd", unsafe(no_mangle))]
fn main() {
    println!("基于飞腾派 + ArceOS 的智能毫米波雷达安防监测系统 demo");

    let mut fan_ctr = fan::FanCtr::new();
    // 配置风扇
    fan_ctr.setup();
    // 启动风扇
    fan_ctr.run();

    let mut led_ctr = led::LEDCtr::new();
    led_ctr.setup();
    led_ctr.disable();

    let mut canfd_ctr = canfd::CanFDCtr::new();
    // 配置 CAN
    canfd_ctr.setup();

    let mut cem5826m11_ctr = cem5826m11::Cam5826M11Ctr::new();
    // 配置 cem5826m11
    cem5826m11_ctr.setup();

    let mut buf = [0; 1024];

    loop {
        let buf_len = cem5826m11_ctr.read(&mut buf);
        let read_data = unsafe { core::str::from_utf8_unchecked(&buf[..buf_len]) };
        println!("cem5826m11 read data {read_data}");

        // todo 添加更复杂的处理逻辑
        let v_value = utils::parse_cem5826m11_data(&buf[..buf_len]);
        if v_value != 0.0 {
            println!("检测到移动目标 value: {v_value} km/h");
            // 点亮 LED
            led_ctr.enable();

            let mut buf = [1, 1, 1, 1, 1, 1, 1, 1];
            // 区分 快速 中速 慢速 首位对应 3 2 1
            match v_value.abs() {
                v if v > 10.0 => {
                    // 风扇设置为高速
                    fan_ctr.set_speed(fan::FanSpeed::High);
                    buf[0] = 3
                }
                v if v > 5.0 => {
                    // 风扇设置为高速
                    fan_ctr.set_speed(fan::FanSpeed::High);
                    buf[0] = 2
                }
                _ => {
                    // 风扇设置为中速
                    fan_ctr.set_speed(fan::FanSpeed::Medium);
                    buf[0] = 1
                }
            }
            canfd_ctr.write(&mut buf);
        } else {
            println!("未检测到移动目标或速度为0");
            // 关闭 LED
            led_ctr.disable();
            // 风扇设置为低速
            fan_ctr.set_speed(fan::FanSpeed::Low);

            // 发送 0 给 CAN
            let mut buf = [0, 0, 0, 0, 0, 0, 0, 0];
            canfd_ctr.write(&mut buf);
        }

        let buf_len = canfd_ctr.read(&mut buf);
        let read_data = unsafe { core::str::from_utf8_unchecked(&buf[..buf_len]) };
        println!("canfd read data {read_data}");
    }
}
